<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<script src="<c:url value="/resources/bootstrap/js/bootstrap-datetimepicker.min.js" />"></script>
<script src="<c:url value="/resources/bootstrap/js/bootstrap-datetimepicker.zh-CN.js" />"></script>
<link rel="stylesheet" href="<c:url value="/resources/bootstrap/css/bootstrap-datetimepicker.css" />">

<style>
    .deleteImg {
        width: 20px;
        position: relative;
        top: 0px;
        left: 20px;
        cursor: pointer;
        display: none;
    }

    .startImg {
        width: 131px;
        height: 32px;
    }
</style>
<div class="main-content">
    <div class="box box-main">
        <form id="maintainOrderForm" model="post" action="<c:url value="/web/admin/maintainOrder/addOrUpdate.action"/>"
              enctype="multipart/form-data"
              method="post" class="form-horizontal">
            <div class="box-body">
                <div class="form-unit">基本信息</div>
                <input type="hidden" id="id" name="id" value="${maintainOrder.id}"/>
                <input type="hidden" name="serial" id="serial" value="${maintainOrder.serial}"/>
                <input type="hidden" name="facilityMaintainSnapIds" id="facilityMaintainSnapIds" />

                <input type="hidden" name="createDate"
                       value="<fmt:formatDate value="${maintainOrder.createDate}" pattern="yyyy-MM-dd HH:mm:ss"/>"/>
                <div class="row">
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                工单编号：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <input  name="orderCode" value="${maintainOrder.orderCode}"
                                        class="form-control" disabled="disabled">
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title=""><span class="required ">*</span>
                                工单名称：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <input name="orderName" value="${maintainOrder.orderName}"
                                       class="form-control required">
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                提醒时间（天）：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <input name="remindTime" value="${maintainOrder.remindTime}"
                                       class="form-control required">
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                紧急程度：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <select id="degree" name="degree" class="form-control required">
                                    <option value="A" <c:if test="${maintainOrder.degree=='A'}">selected</c:if>>A
                                    </option>
                                    <option value="B" <c:if test="${maintainOrder.degree=='B'}">selected</c:if>> B
                                    </option>
                                    <option value="C" selected>C</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <%--<div class="col-xs-6">--%>
                        <%--<div class="form-group">--%>
                            <%--<label class="control-label col-sm-4" title=""><span class="required ">*</span>--%>
                                <%--开始时间：<i class="fa icon-question hide"></i></label>--%>
                            <%--<div class="col-sm-8">--%>
                                <%--<input name="start" id="start"--%>
                                       <%--value="<fmt:formatDate value="${maintainOrder.startDateTime}" pattern="yyyy-MM-dd HH:mm"/>"--%>
                                       <%--class="form-control Wdate required" autoComplete="off">--%>
                            <%--</div>--%>
                        <%--</div>--%>
                    <%--</div>--%>
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title=""><span class="required ">*</span>
                                结束时间：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <input name="end" id="end" value="<fmt:formatDate value="${maintainOrder.endDateTime}" pattern="yyyy-MM-dd HH:mm"/>"
                                       class="form-control Wdate required" autoComplete="off">
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                维保类型：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <select id="type" name="type" class="form-control required">
                                    <option value="深度维护保养" <c:if test="${maintainOrder.type=='深度维护保养'}">selected</c:if>>
                                        深度维护保养
                                    </option>
                                    <option value="中度维护保养" <c:if test="${maintainOrder.type=='中度维护保养'}">selected</c:if>>
                                        中度维护保养
                                    </option>
                                    <option value="简单维护保养" selected>简单维护保养</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                标准工分：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <input name="points" value="${maintainOrder.points}"
                                       class="form-control">
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                所属部门：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <input id="selectOrganizationId" name="selectOrganizationId" path="selectOrganizationId" class="form-control">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                完成审批流：<i
                                    class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <input id="selectCompleteAuditFlowId" name="selectCompleteAuditFlowId" path="selectCompleteAuditFlowId"
                                       class="form-control">
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                延期审批流：<i
                                    class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <input id="selectDelayAuditFlowId" name="selectDelayAuditFlowId" path="selectDelayAuditFlowId"
                                       class="form-control">
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                取消审批流：<i
                                    class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <input id="selectCancelAuditFlowId" name="selectCancelAuditFlowId" path="selectCancelAuditFlowId"
                                       class="form-control">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-xs-12">
                        <div class="form-group">
                            <div class="form-group">
                                <label class="control-label col-sm-2" title="">
                                    安全要求：<i class="fa icon-question hide"></i></label>
                                <div class="col-sm-9">
                                    <textarea name="required" rows="4" maxlength="200"
                                              class="form-control">${maintainOrder.required}</textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                安全指导书开关：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <input type="checkbox" class="form-control" id="safeInstruction"
                                       name="safeInstruction"
                                       <c:if test="${maintainOrder.safeInstruction==true}">checked</c:if>
                                       style="margin-top: auto;margin-bottom: auto"/>
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-6">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                上传安全指导书：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <div style="width: 300px;">
                                    <img class="startImg" id="img1"
                                         src="<c:url value="/resources/images/pdfUpLoad.png" />"
                                         onclick="$('#pic1').click();"/>（只支持PDF格式）
                                    <input type="file" style="display: none;" name="pic1" id="pic1"
                                           onchange="getimgload(1)"/>
                                    <label class="control-label col-sm-12" title="">
                                        <%--<a href="${filePath}" id="filePath" class="showFileName" target="_blank"></a>--%>
                                        <span class="showFileName"></span>
                                        <img class="deleteImg" id="delete1"
                                             src="<c:url value="/resources/images/delete.png"/>"
                                             onclick="delectImg(1)"/>
                                    </label>
                                    <input type="hidden" id="sImg1" name="sImg1" value="0"/><%--判断有没有变更图片用的 变了就为1 不变就为0--%>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-unit">设备——工作要求</div>
                    <div class="col-xs-12">
                        <div class="form-group" style="margin-left: 6%">
                            <div class="col-xs-12">
                                <label class="btn  btn-primary" id="addFacility"><i
                                        class="icon-plus"></i>
                                    添加设备
                                </label>&nbsp;&nbsp;
                                <label class="btn  btn-primary" id="addMaintain"><i
                                        class="icon-plus"></i>
                                    选择工作要求
                                </label>&nbsp;&nbsp;
                                <label class="btn  btn-primary" id="removeMaintain"><i
                                        class="fa fa-trash-o"></i>
                                    清除已选择工作要求
                                </label>&nbsp;&nbsp;
                                <label class="btn  btn-primary" id="remove"><i
                                        class="fa fa-trash-o"></i>
                                    删除
                                </label>&nbsp;&nbsp;
                            </div>
                        </div>
                    </div>
                    <div class="ml10 mr10">
                        <table id="facilityMaintainSnapDataGrid"></table>
                        <%--<div id="facilityMaintainSnapDataGridPage"></div>--%>
                    </div>
                </div>
            </div>
            <div class="box-footer">
                <div class="row">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-sm btn-primary" id="btnSubmit"><i
                                class="fa fa-check"></i>
                            保 存
                        </button>&nbsp;

                        <button type="button" class="btn btn-sm btn-default" id="btnCancel" onclick="closeView()"><i
                                class="fa fa-times"></i> 关 闭
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>


<script>
    $("#maintainOrderForm").validate({
        submitHandler: function (form) {
            var ids = $("#facilityMaintainSnapDataGrid").getDataIDs();
            //设备必须选择
            if(ids.length==0){
                js.showMessage("请添加设备");
                return false;
            }
            //工作要求必填
            var flag=0;
            $.each(ids,function(i,item){
                var ret =$("#facilityMaintainSnapDataGrid").jqGrid('getRowData', item);
                var maintainId =ret.maintainId;
                console.log(maintainId)
                if(maintainId==null || maintainId==""){
                    flag=1;
                }
            });
            if(flag==1){
                js.showMessage("还存在未添加工作要求的设备，请完善数据");
                return false
            }

            $("#facilityMaintainSnapIds").val(JSON.stringify(ids));
            console.log(JSON.stringify(ids));
            js.ajaxSubmitForm($(form), function (data) {
                js.showMessage(data.msg);
                if (data.status == Global.NO) {
                    closeView();
                    $('#dataGrid').dataGrid("refresh");
                }
            }, "json");
        }
    });
    var date = new Date();
    // $("#start").datetimepicker({
    //     format: 'yyyy-mm-dd hh:ii',
    //     startDate: date,
    //     minuteStep:1,
    //     autoclose:true,//选中关闭
    //     todayBtn: true//今日按钮
    // });
    $("#end").datetimepicker({
        format: 'yyyy-mm-dd hh:ii',
        startDate: date,
        minuteStep:1,
        autoclose:true,//选中关闭
        todayBtn: true//今日按钮
    });

    // // 时间选择器互动（结束时间不得早于开始时间）
    // $("#start").on('changeDate', function(ev) {
    //     $("#end").datetimepicker('setStartDate', ev.date);
    //     var d = $("#end").val();
    //     if (d) {
    //         var date = new Date(d.replace(/-/g, '/'));
    //         if (date != 'Invalid Date' && date < ev.date) {
    //             $("#end").datetimepicker('setDate', ev.date)
    //         }
    //     }
    // });

    $('#safeInstruction').bootstrapSwitch({
        onText: "开",
        offText: "关",
        onColor: "success",
        offColor: "info",
    });

    function delectImg(id) {
        $("#sImg" + id).val('1');
        $("#pic" + id).val('');
        $(".showFileName").html("");
        $("#img" + id).attr("src", "<c:url value="/resources/images/pdfUpLoad.png" />");
        $("#delete" + id).hide();
    }

    function getimgload(id) {
        var filePath = $('#pic1').val();
        var arr = filePath.split('\\');
        var fileName = arr[arr.length - 1];

        var obj = document.getElementById("pic" + id);
        var stuff = obj.value.match(/^(.*)(\.)(.{1,8})$/)[3];
        if (stuff != 'pdf') {
            alert('只支持pdf文件');
            return false;
        }

        // $("#filePath").attr('href','');
        $(".showFileName").html(fileName);
        $("#sImg" + id).val('1');//表示图片变更了（总之不是原来的图片了）
        $("#delete" + id).show();
    }

    $(function () {
        if (${fileName != null && fileName != ''}) {
            $(".showFileName").html('${fileName}');
            $("#delete1").show();
        }
    });



    function closeView() {
        layer.close(LayWin['wMaintainOrder']);
    }
    //所属部门
    var selectOrganizationId = $('#selectOrganizationId').magicSuggest({
        allowFreeEntries: false,
        data: '<c:url value="/web/admin/organization/getOrganizationListMagic.action?id=${maintainOrder.organization.id}" />',
        queryParam: 'q',
        valueField: "value",
        displayField: "text",
        maxSelection: 1,
        noSuggestionText: '',
        placeholder: '请选择',
        required: true,
        autoSelect: true,
        selectFirst: true,
        value: magicSuggestValue('${maintainOrder.organization.id}')
    });
    //完成审批
    var selectCompleteAuditFlowId = $('#selectCompleteAuditFlowId').magicSuggest({
        allowFreeEntries: false,
        data: '<c:url value="/web/admin/auditFlow/getAuditFlowSelect.action?type=complete&&flag=2" />',
        queryParam: 'q',
        valueField: "value",
        displayField: "text",
        maxSelection: 1,
        noSuggestionText: '',
        placeholder: '请选择',
        required: true,
        autoSelect: true,
        selectFirst: true,
        value: magicSuggestValue('${maintainOrder.auditCompleteID}')
    });
    //延期审批
    var selectDelayAuditFlowId = $('#selectDelayAuditFlowId').magicSuggest({
        allowFreeEntries: false,
        data: '<c:url value="/web/admin/auditFlow/getAuditFlowSelect.action?type=delay&&flag=2" />',
        queryParam: 'q',
        valueField: "value",
        displayField: "text",
        maxSelection: 1,
        noSuggestionText: '',
        placeholder: '请选择',
        required: true,
        autoSelect: true,
        selectFirst: true,
        value: magicSuggestValue('${maintainOrder.delayFlowID}')
    });
    //延期审批
    var selectCancelAuditFlowId = $('#selectCancelAuditFlowId').magicSuggest({
        allowFreeEntries: false,
        data: '<c:url value="/web/admin/auditFlow/getAuditFlowSelect.action?type=cancel&&flag=2" />',
        queryParam: 'q',
        valueField: "value",
        displayField: "text",
        maxSelection: 1,
        noSuggestionText: '',
        placeholder: '请选择',
        required: true,
        autoSelect: true,
        selectFirst: true,
        value: magicSuggestValue('${maintainOrder.cancelFlowID}')
    });


    $(document).ready(function () {
        $("#facilityMaintainSnapDataGrid").jqGrid({
            url:"<c:url value="/web/admin/maintainOrder/facilityMaintainSnapJson.action?maintainOrderId=${maintainOrder.id}&&serial=${maintainOrder.serial}" />",
            datatype: "json",
            multiselect: true,
            autowidth:true,
            rowNum: 1000,
            colNames : ['id' ,'工艺id','设备名称', '设备编号','规格型号', '工艺名称', '安全要求', '设备类型','设备类型ID' ],
            colModel : [
                {name : 'id',index : 'id',width :50,align: "center"},
                {name : 'maintainId',index : 'maintainId', hidden:true,width : 150,align: "center",sortable: false},
                {name : 'facilityName',index : 'facilityName',width : 100,align: "center" ,sortable: false},
                {name : 'facilityCode',index : 'facilityCode',width : 100,align: "center",sortable: false},
                {name : 'spec',index : 'spec',width : 150,align: "center",sortable: false},
                {name : 'maintainName',index : 'maintainName',width : 150,align: "center",sortable: false},
                {name : 'safety',index : 'safety',width : 200,align: "center",sortable: false},
                {name : 'facilityCatName',index : 'facilityCatName',width : 100,align: "center",sortable: false},
                {name : 'facilityCatId',index : 'facilityCatId',width : 100,align: "center",sortable: false,hidden:true},
            ],

            ajaxSuccess: function(data){

            }
        });
    });


    //添加设备
    $("#addFacility").click(function () {
        vLayuiUtil.openLayerIframWindow('wFacilityEdit', '<c:url value="/web/admin/maintainOrder/addFacilityList.action?serial=${maintainOrder.serial}&&maintainOrderId=${maintainOrder.id}" />', '添加设备',['70%', '95%'])
    });
    //添加工艺
    $("#addMaintain").click(function () {
        var ids = $("#facilityMaintainSnapDataGrid").jqGrid("getGridParam", "selarrrow");
        if(ids.length==0){
            js.showMessage("请选择要添加工作要求的设备");
            return false;
        }
        var flag=0;
        var catId="";
        if(ids.length>=1){
            $.each(ids, function (i, item) {
                var ret = $("#facilityMaintainSnapDataGrid").jqGrid('getRowData', item);
                if(ret.facilityCatId!=""){
                    if(catId==""){
                        catId = ret.facilityCatId;
                    }else{
                        if(catId!=ret.facilityCatId){
                            flag=1;
                        }
                    }
                }

            });
            if(flag==1){
                js.showMessage("所选择的设备中存在类型不一致，请选择相同的设备类型添加工作要求");
                return false;
            }
        }
        vLayuiUtil.openLayerIframWindow('wMaintain', '<c:url value="/web/admin/maintainOrder/addMaintainList.action?maintainOrderId=${maintainOrder.id}&&facilityMaintainSnapIds=" />'+ids+"&&catId="+catId, '添加工作要求',['70%', '95%'])
    });

    //清除工艺
    $("#removeMaintain").click(function () {
        var ids = $("#facilityMaintainSnapDataGrid").jqGrid("getGridParam", "selarrrow");
        if(ids.length==0){
            js.showMessage("请选择要清除工作要求的数据");
            return false;
        }
        $.ajax({
            type: 'post',
            url: "<c:url value="/web/admin/maintainOrder/removeMaintain.action" />",
            data: {"facilityMaintainSnapIds": JSON.stringify(ids)},
            dataType: 'json',
            async: false,
            success: function (data) {
                js.showMessage(data.msg);
                $("#facilityMaintainSnapDataGrid").jqGrid().trigger('reloadGrid');
            },
            error: function () {
                js.showMessage("出错了，请联系管理员");
            }
        });

    });


    /**
     * 清除数据
     */
    $("#remove").click(function () {
        var ids = $("#facilityMaintainSnapDataGrid").jqGrid("getGridParam", "selarrrow");
        if(ids.length==0){
            js.showMessage("请选择要删除的数据");
            return false;
        }
        $.ajax({
            type: 'post',
            url: "<c:url value="/web/admin/maintainOrder/deleteFacilityMaintainSnap.action" />",
            data: {"facilityMaintainSnapIds": JSON.stringify(ids)},
            dataType: 'json',
            async: false,
            success: function (data) {
                js.showMessage(data.msg);
                $("#facilityMaintainSnapDataGrid").jqGrid().trigger('reloadGrid');
            },
            error: function () {
                js.showMessage("出错了，请联系管理员");
            }
        });
    })


</script>


